<?php


namespace Hkw\TencentLatlng\Form;


use Dcat\Admin\Admin;
use Dcat\Admin\Form\Field;

class TencentLatlng extends Field
{
    protected $view = 'hkw-form-tencentlatlng::index';
    protected $autoPosition = false;
    protected $column = [];
    protected $height = 500;
    protected $zoom = 18;


    public function __construct($column, $arguments)
    {
        $this->column['lat'] = (string)$column;
        $this->column['lng'] = (string)$arguments[0];

        array_shift($arguments);

        $this->label = $this->formatLabel($arguments);
    }

    public function render()
    {
        $variables = [
            'height' => $this->height,
            'zoom'   => $this->zoom
        ];
        Admin::script(<<<JS
    $('meta[name="referrer"]').attr('content','strict-origin-when-cross-origin');//修复Autocomplete无效的bug
    //定义函数
    /*typeof createVar === 'undefined' && function createVar(vname){
        
    }*/
    if (typeof map_arr === 'undefined'){
        var map_arr = {};
    }
    map_arr["{$this->column['lat']}{$this->column['lng']}"] = {};
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['lat'] = $("#{$this->column['lat']}");
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['lng'] = $("#{$this->column['lng']}");
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['keyword'] = '';
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['uuid'] = "{$this->column['lat']}{$this->column['lng']}";
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['marker'] = null;
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['city'] = null;
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['center'] = null;
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['map'] = null;
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['ipLocation'] = new TMap.service.IPLocation();
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['search'] = new TMap.service.Search({ pageSize: 10 });
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['setMarker'] = function(position){
        if (this.marker) {
            this.marker.setMap(null);
            this.marker = null;
        }
        this.marker = new TMap.MultiMarker({
            map: this.map,
            styles: {
                "marker": new TMap.MarkerStyle({
                    "width": 25,
                    "height": 35,
                    "anchor": { x: 16, y: 32 },
                    "src": 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
                })
            },
            geometries: [{
                "styleId": 'marker',
                "position": position,
                "properties": {
                    "title": "marker"
                }
            }]
        });
        this.lat.val(position.getLat());
        this.lng.val(position.getLng());
    };
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['searchByKeyword'] = function(keyword){
       this.search.searchRegion({
          keyword: keyword,
          cityName: this.city,
          autoExtend:true
        }).then((result) => {
            if (result.data.length > 0){
                this.setMarker(result.data[0].location);
                this.map.setCenter(result.data[0].location);
            }
        });
    };
    
    map_arr["{$this->column['lat']}{$this->column['lng']}"]['init'] = function(){
        if( ! this.lat.val() || ! this.lng.val()) {
            this.center = new TMap.LatLng(39.984104, 116.307503);
        }else{
            this.center = new TMap.LatLng(this.lat.val(),this.lng.val());
        }
        this.map = new TMap.Map("map_"+this.uuid, {
            center: this.center,
            zoom: {$this->zoom}
        });
        if( ! this.lat.val() || ! this.lng.val()) {
            this.ipLocation.locate({}).then((ip_location) => {
               let { result } = ip_location;
               this.city = result.ad_info.city
               this.map.setCenter(result.location);
               this.center = result.location;
            })
        }
        this.map.on("click", (evt) => {
            this.setMarker(evt.latLng);              
        });
        $(document).undelegate('#searchbtn-'+this.uuid,'click').delegate('#searchbtn-'+this.uuid,'click',(e)=>{
            console.log($("#search-"+this.uuid).val());
            this.searchByKeyword($("#search-"+this.uuid).val());
        });
        if(this.lat.val() && this.lng.val()) {
            this.setMarker(new TMap.LatLng(this.lat.val(),this.lng.val()))
        }
    };
    map_arr["{$this->column['lat']}{$this->column['lng']}"].init();
JS
);
        $this->addVariables($variables);
        return parent::render();
    }

    /**
     * Set map height.
     *
     * @param int $height
     * @return $this
     */
    public function height(int $height)
    {
        $this->height = $height;

        return $this;
    }

    /**
     * Set map zoom.
     *
     * @param int $zoom
     * @return $this
     */
    public function zoom(int $zoom)
    {
        $this->zoom = $zoom;

        return $this;
    }

    /**
     * Set true to automatically get the current position from the browser on page load
     * @param $bool
     * @return $this
     */
    public function setAutoPosition($bool)
    {
        $this->autoPosition = $bool;
        return $this;
    }

    public static function requireAssets()
    {
        Admin::js('//map.qq.com/api/gljs?v=1.exp&key=' . config('admin.map.keys.tencent') . '&libraries=service');
    }

}